// Package repository
// Created by GoLand
// @User: lenora
// @Date: 2024/8/19
// @Time: 09:57

package repository

import (
	"camp/microbook/internal/domain"
	"camp/microbook/internal/repository/dao"
	"context"
	"time"
)

type CronJobRepository interface {
	Preempt(ctx context.Context) (domain.Job, error)
	Release(ctx context.Context, id uint64) error
	ResetNextTime(ctx context.Context, id uint64, nextTime time.Time) error
}

type PreemptJobRepository struct {
	dao dao.JobDAO
}

func NewPreemptJobRepository(dao dao.JobDAO) CronJobRepository {
	return &PreemptJobRepository{dao: dao}
}

func (repo *PreemptJobRepository) Preempt(ctx context.Context) (domain.Job, error) {
	res, err := repo.dao.Preempt(ctx)
	return repo.toDomain(res), err
}

func (repo *PreemptJobRepository) Release(ctx context.Context, id uint64) error {
	return repo.dao.Release(ctx, id)
}

func (repo *PreemptJobRepository) ResetNextTime(ctx context.Context, id uint64, nextTime time.Time) error {
	return repo.dao.ResetNextTime(ctx, id, nextTime)
}

func (repo *PreemptJobRepository) toDomain(job dao.Job) domain.Job {
	return domain.Job{
		Id:       job.Id,
		Executor: job.Executor,
		Spec:     job.Spec,
	}
}
